<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="props.width"
    :height="props.height" @ok="handleSubmit">
    <a-row>
      <a-col :span="22">
        <BasicForm @register="registerForm" />
      </a-col>
    </a-row>
  </BasicModal>
</template>

<script lang="ts" setup>
import { ref, computed, unref } from 'vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form/index';
import { FormSchema } from '/@/components/Table';
// Emits声明
const emit = defineEmits(['register', 'success']);
const isUpdate = ref(false);

//页面属性
const props = defineProps({
  width: { type: Number, default: 500 },
  height: { type: Number, default: 200 },
  schemas: { type: Array as PropType<FormSchema[]> },
  apiUrl: { type: Function as PropType<Fn> },
  pid: { require: true, type: String },
});

var title = ref('凭证提交');

//表单配置
const [registerForm, { setProps, resetFields, setFieldsValue, validate }] = useForm({
  labelWidth: 130,
  schemas: props.schemas,
  showActionButtonGroup: false,
  baseColProps: { span: 24 },
});

var ids = ref([]);
//表单赋值
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  //重置表单
  await resetFields();
  //加载单行数据
  if (data?.record) {
    isUpdate.value = !!data?.isUpdate;
    //标题
    title.value = data?.title;
    //表单赋值
    setFieldsValue({
      ...data.record
    });
  }
  //加载多行数据
  if (data?.ids) {
    //标题
    title.value = data?.title;
    ids.value = data?.ids;
    //表单赋值
    setFieldsValue({
      ids: data?.ids,
    });
  }
});
//表单提交事件
async function handleSubmit(v) {
  try {
    let values = await validate();
    setModalProps({ confirmLoading: true });

    //判断是否有父级数据
    values.pid = values.pid ? values.pid : props.pid;
    //提交表单
    await props.apiUrl({ ...values, ids: ids.value }, isUpdate.value);
    //关闭弹窗
    closeModal();
    //刷新列表
    emit('success');
  } finally {
    setModalProps({ confirmLoading: false });
  }
}
</script>

<style lang="less" scoped>
/** 时间和数字输入框样式 */
:deep(.ant-input-number) {
  width: 100%;
}

:deep(.ant-calendar-picker) {
  width: 100%;
}
</style>
